package com.dmgis.qxfw.dataservice.businessservice.nyfw.controller;

import com.alibaba.fastjson.JSONObject;
import com.dmgis.entity.DmMapPoint;
import com.dmgis.qxfw.dataservice.businessservice.api.domain.RequestDataBySelect;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.ny.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.qx.*;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.default_station;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.xt.users;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.country_point;
import com.dmgis.qxfw.dataservice.businessservice.api.entity.yj.county_point;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ActualElemQuery;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.CityFcstInfo;
import com.dmgis.qxfw.dataservice.businessservice.common.domain.ResultObj;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.ActualData;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.ForecastInfo;
import com.dmgis.qxfw.dataservice.businessservice.common.entity.TownshipForecastKey;
import com.dmgis.qxfw.dataservice.businessservice.common.util.*;
import com.dmgis.qxfw.dataservice.businessservice.controller.ProcessRequestController;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.FileRequestService;
import com.dmgis.qxfw.dataservice.businessservice.dmgis_mongodb_srv.dataservice.service.Impl.MongoService1;
import com.dmgis.qxfw.dataservice.businessservice.nyfw.service.IFarmIndexService;
import com.dmgis.qxfw.dataservice.businessservice.nyfw.service.IFarmInfoService;
import com.dmgis.qxfw.dataservice.businessservice.qxinfo.service.IQxInfoService;
import com.dmgis.qxfw.dataservice.commonservice.common.DbConfig;
import com.dmgis.qxfw.dataservice.gisservice.service.ITransformService;
import com.fasterxml.jackson.core.type.TypeReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
* @Description: 信息展示模块（游客登录）
* @Author: sunshine
* @Date: 2021/7/27 13:18
**/
@Controller
@RequestMapping("/youke/nyfw")
public class FarmIndexController {
    @Resource
    private IFarmIndexService farmIndexService;

    @Resource
    private IFarmInfoService farmInfoService;

    @Resource
    private IQxInfoService qxInfoService;

    @Resource
    private ITransformService transformService;

    ProcessRequestController pc = new ProcessRequestController();


    private  final String operatingSystem;

    @Autowired
    public FarmIndexController(String operatingSystem) {
        this.operatingSystem = operatingSystem;
    }

    //MongoService1 ms = new MongoService1();
    FileRequestService ms = new FileRequestService();
    /***
     * 得到最新预报滚屏公告
     * @return
     */
    @RequestMapping("/getBroadcast")
    @ResponseBody
    public Object getBroadcast(HttpServletRequest request) {
        ArrayList<Object> msg = new ArrayList<Object>();
        msg.add(farmIndexService.getForecast());
        msg.add(farmIndexService.getWarning());
        ResultObj resultObj = new ResultObj("查询成功", msg, true);
        return resultObj;
    }


    /***
     * 得到站点信息
     * @return
     */
    @RequestMapping("/getStationInfo")
    @ResponseBody
    public Object getStationInfo(HttpServletRequest request) {
        List<StationInfo> msg = farmIndexService.getStationInfo();
        ResultObj resultObj = new ResultObj("查询成功", msg, true);
        return resultObj;
    }

    /***
     * 获取实况信息
     * @return
     */
    @RequestMapping("/getWeather")
    @ResponseBody
    public Object getWeather(HttpServletRequest request) {
        String stationid = request.getParameter("stationid");
        String msg = farmIndexService.getWeather(stationid);
        ResultObj resultObj = new ResultObj("查询成功", msg, true);
        return resultObj;
    }

    /***
     * 获取底部支持
     * @return
     */
    @RequestMapping("/getSupport")
    @ResponseBody
    public Object getSupport(HttpServletRequest request) {
        Wangzhan msg = farmIndexService.getSupport();
        if (msg == null)
            return new ResultObj("查询失败", msg, false);
        else
            return new ResultObj("查询成功", msg, true);
    }

    /**
     * @Description: * 1.获取当前日期所有站点的所有农事活动
     * * 2.然后根据农事活动分类来筛选出对应种类的农事活动
     * @Author: sunshine
     * @Date: 2021/7/22 14:04
     **/
    @RequestMapping("/getArgiSrvFcst")
    @ResponseBody
    public Object getArgiSrvFcst(HttpServletRequest request) {
        DateTime nowDate = DateTime.now();
        String date = nowDate.toDateString();//当前日期
        //处理得到时效
        String timeChar = "";
        if (nowDate.GetHour() >= 8 && nowDate.GetHour() < 20) {
            timeChar = "08";
        } else if (nowDate.GetHour() < 8) {
            timeChar = "20";
            date = nowDate.AddDays(-1).toDateString();//注意获取前一天的预报
        } else {
            timeChar = "20";
        }
        //根据用户session获取用户的站点编号和站点名称,如果没有则使用默认站点
        String nyStaName = request.getParameter("nyStaName");
        Object agrisrvList = farmIndexService.getArgiSrvFcst(date, timeChar, nyStaName);
        return agrisrvList;
    }

    /**
     * @Description: 农情监控  type=0 首页的    首页的农情监控和点击详情之后的
     * @Author: sunshine
     * @Date: 2021/7/22 15:46
     **/
    @RequestMapping("/getArgiMonitor")
    @ResponseBody
    public Object getArgiMonitor(HttpServletRequest request) {
        String type = request.getParameter("type");
        Object agrisrvList = farmIndexService.getArgiMonitor(type);
        return agrisrvList;
    }

    /**
     * @Description: 政务信息 文章类别和文章内容
     * 政务信息  bid 3  sid 9
     * 农气新闻  bid 1  sid 5
     * 政务信息 BigType 再根据id=9
     * 农气新闻 获取第一篇文章 type=1&BigType
     * 农气新闻 获取第一篇文章详情 type=1&BigType&FirstId
     * @Author: sunshine
     * @Date: 2021/7/22 15:54
     **/
    @RequestMapping("/getArgiZwxx")
    @ResponseBody
    public Object getArgiZwxx(HttpServletRequest request) {
        String BigType = request.getParameter("BigType");
        String Smalltype = request.getParameter("smalltype");
        String type = request.getParameter("type");//获取第一篇文章
        String FirstId = request.getParameter("FirstId");//获取第一篇文章
        Object agrisrvList = farmIndexService.getArgiZhengFa(BigType, type, FirstId, Smalltype,request);
        return agrisrvList;
    }

    /**
     * @Description: 增加点击量
     * @Author: sunshine
     * @Date: 2021/7/22 16:16
     **/
    @RequestMapping("/SetZhengFaClick")
    @ResponseBody
    public Object SetZhengFaClick(HttpServletRequest request) {
        String id = request.getParameter("id");
        String click = request.getParameter("click");
        String ishuandeng = request.getParameter("ishuandeng");
        String sort = request.getParameter("sort");
        Addwendang updateData = new Addwendang();
        updateData.setClick(Long.parseLong(click));
        updateData.setIshuandeng(Long.parseLong(ishuandeng));
        updateData.setSort(Long.parseLong(sort));
        Object agrisrvList = farmIndexService.SetZhengFaClick(updateData, id);
        return agrisrvList;
    }

    /**
     * @Description: 绑定发育期信息
     * @Author: sunshine
     * @Date: 2021/7/22 17:32
     **/
    @RequestMapping("/BindNongQi")
    @ResponseBody
    public Object BindNongQi(@RequestParam("params") String params,HttpServletRequest request) {
        try {
            Map<String, String> selectParam = new HashMap<String, String>();
            RequestDataBySelect selectRequest = new RequestDataBySelect();
            List<StationInfo> stationInfos = new ArrayList<>();
            List<users> usersList = new ArrayList<>();
            List<Coordinator> coordinatorList = new ArrayList<>();
            List<Infocollector> infocollectors = new ArrayList<>();
            List<DefaultStation> defaultStations = new ArrayList<>();
            users user = null;
            if (!StringUtil.IsNullOrEmpty(params)) {
                //登录
                JSONObject jsonObject = JSONObject.parseObject(params);
                user = jsonObject.getObject("user", users.class);
                //农业局 或 农业大户
                if (!StringUtil.IsNullOrEmpty(user.getType())) {
                    if ("1".equals(user.getType())) {
                        selectRequest.setParam("username='" + user.getUsername() + "' and type='农业局'");
                    }
                    if ("4".equals(user.getType())) {
                        selectRequest.setParam("username='" + user.getUsername() + "' and type='农业大户'");
                    }
                    selectParam.put("method", "users");
                    selectParam.put("advCode", DbConfig.advCode);
                    selectParam.put("sqlType", "select");
                    selectParam.put("param", JsonUtil.object2Json(selectRequest));
                    String message = pc.processRequest(selectParam);
                    usersList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<users>>() {
                    });
                }
                //协理员
                if ("3".equals(user.getType())) {
                    selectRequest.setParam("coordinatename='" + user.getUsername() + "'");
                    selectParam.put("method", "coordinator");
                    selectParam.put("advCode", DbConfig.advCode);
                    selectParam.put("sqlType", "select");
                    selectParam.put("param", JsonUtil.object2Json(selectRequest));
                    String message = pc.processRequest(selectParam);
                    coordinatorList = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<Coordinator>>() {
                    });
                }
                //信息员
                if ("2".equals(user.getType())) {
                    selectRequest.setParam("infocollectorname='" + user.getUsername() + "'");
                    selectParam.put("method", "infocollector");
                    selectParam.put("advCode", DbConfig.advCode);
                    selectParam.put("sqlType", "select");
                    selectParam.put("param", JsonUtil.object2Json(selectRequest));
                    String message = pc.processRequest(selectParam);
                    infocollectors = JsonUtil.jsonStr2TypeReference(message, new TypeReference<List<Infocollector>>() {
                    });
                }
                 if("".equals(user.getUsername())) {
                    //游客 查询默认站点表
                    selectParam = new HashMap<String, String>();
                    selectRequest = new RequestDataBySelect();
                    selectParam.put("method", "default_station");
                    selectParam.put("advCode", DbConfig.advCode);
                    selectParam.put("sqlType", "select");
                    selectParam.put("param", JsonUtil.object2Json(selectRequest));
                    String message1 = pc.processRequest(selectParam);
                    defaultStations = JsonUtil.jsonStr2TypeReference(message1, new TypeReference<List<DefaultStation>>() {
                    });
                }
            }
            if (usersList != null && usersList.size() > 0) {
                selectParam = new HashMap<String, String>();
                selectRequest = new RequestDataBySelect();
                selectRequest.setParam("stationid='" + usersList.get(0).getStationid() + "'");
                selectParam.put("method", "station_info");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("sqlType", "select");
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                 String message1 = pc.processRequest(selectParam);
                stationInfos = JsonUtil.jsonStr2TypeReference(message1, new TypeReference<List<StationInfo>>() {
                });
            }
            if (coordinatorList != null && coordinatorList.size() > 0) {
                Coordinator coordinator = coordinatorList.get(0);
                selectParam = new HashMap<String, String>();
                selectRequest = new RequestDataBySelect();
                selectRequest.setParam("stationid='" + coordinator.getStationid() + "'");
                selectParam.put("method", "station_info");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("sqlType", "select");
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message2 = pc.processRequest(selectParam);
                stationInfos = JsonUtil.jsonStr2TypeReference(message2, new TypeReference<List<StationInfo>>() {
                });
            }
            if (infocollectors != null && infocollectors.size() > 0) {
                Infocollector infocollector = infocollectors.get(0);
                selectParam = new HashMap<String, String>();
                selectRequest = new RequestDataBySelect();
                selectRequest.setParam("stationid='" + infocollector.getStationid() + "'");
                selectParam.put("method", "station_info");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("sqlType", "select");
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message2 = pc.processRequest(selectParam);
                stationInfos = JsonUtil.jsonStr2TypeReference(message2, new TypeReference<List<StationInfo>>() {
                });
            }
            if (defaultStations != null && defaultStations.size() > 0) {
                DefaultStation defaultStation = defaultStations.get(0);
                selectParam = new HashMap<String, String>();
                selectRequest = new RequestDataBySelect();
                selectRequest.setParam("stationid='" + defaultStation.getDefaultstationid() + "'");
                selectParam.put("method", "station_info");
                selectParam.put("advCode", DbConfig.advCode);
                selectParam.put("sqlType", "select");
                selectParam.put("param", JsonUtil.object2Json(selectRequest));
                String message2 = pc.processRequest(selectParam);
                stationInfos = JsonUtil.jsonStr2TypeReference(message2, new TypeReference<List<StationInfo>>() {
                });
            }
                StationInfo stationInfo = stationInfos.get(0);
                String stationid = stationInfo.getStationid();
                String stationname = stationInfo.getStationname();
                String forecaststationid = stationInfo.getForecaststationid();
                Object agrisrvList = farmIndexService.BindNongQi(stationid, stationname, forecaststationid);
                return agrisrvList;
        }catch (Exception ex){
            return new ResultObj("查询失败", ex.getMessage(), true);
        }
    }

    /**
     * @Description: 查询土壤湿度站点
     * @Author: sunshine
     * @Date: 2021/7/23 15:32
     **/
    @RequestMapping("/GetSoilHumiditySta")
    @ResponseBody
    public Object GetSoilHumiditySta(HttpServletRequest request) {
        Object agrisrvList = farmIndexService.GetSoilHumiditySta();
        return agrisrvList;
    }

    /**
     * @Description: 土壤湿度
     * 根据开始时间和结束时间查询行政区划内所有有数据的站点
     * @Author: sunshine
     * @Date: 2021/7/23 10:54
     **/
    @RequestMapping("/GetSoilHumidity")
    @ResponseBody
    public Object GetSoilHumidity(HttpServletRequest request) {
        String startDate = request.getParameter("startDate");
        String endDate = request.getParameter("endDate");
        String stationId = request.getParameter("stationId");
        List<soil_humidity> resultList = farmIndexService.GetSoilHumidity(startDate, endDate, stationId);
        String level = "";
        List<String> hours = new ArrayList<String>();
        List<String> times = new ArrayList<String>();
        Map<String, List<Double>> stationValMap1 = new HashMap<String, List<Double>>();
        for (int i = 0; i < resultList.size(); i++) {
            level = String.valueOf(resultList.get(i).getLevel());
            if (level.equals(String.valueOf(resultList.get(0).getLevel()))) {
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("dd HH");
                String time = simpleDateFormat.format(resultList.get(i).getObservetime());
                hours.add(time);
                SimpleDateFormat simpleDateFormat1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                times.add(simpleDateFormat1.format(resultList.get(i).getObservetime()));
            }
            List<Double> values1 = new ArrayList<Double>();
            if (!stationValMap1.keySet().contains(level)) {
                if (resultList.get(i).getRelhumidity() != 0 && resultList.get(i).getRelhumidity() != -65535) {
                    values1.add(resultList.get(i).getRelhumidity());
                    stationValMap1.put(level, values1);
                } else {
                    values1.add(0.0);
                }
            } else {
                if (resultList.get(i).getRelhumidity() != 0 && resultList.get(i).getRelhumidity() != -65535) {
                    stationValMap1.get(level).add(resultList.get(i).getRelhumidity());
                }
            }
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        result.add(times);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        return new ResultObj("查询成功", result, true);
    }

    /**
     * @Description: 获取农气预报
     * @Author: sunshine
     * @Date: 2021/7/23 13:30
     **/
    @RequestMapping("/GetArgiFast")
    @ResponseBody
    public Object GetArgiFast(HttpServletRequest request) {
        String nstype = request.getParameter("nstype");
        Object agrisrvList = farmIndexService.GetArgiFast(nstype, request);
        return agrisrvList;
    }

    /**
     * @Description: 获取视频列表
     * @Author: sunshine
     * @Date: 2021/7/23 16:43
     **/
    @RequestMapping("/GetVideoList")
    @ResponseBody
    public Object GetVideoList(HttpServletRequest request) {
        String id = request.getParameter("id");
        //查询pg表 模糊查询
        List<Video> videos = farmInfoService.getVideoById(id);
        try {
            for (Video vdeo : videos) {
                String serviceFilePath = "";
                // 下载
                String fileName = vdeo.getVideopath();
                String path = request.getContextPath();
                String basePath = DbConfig.IP + path
                        + "/Temp/Video/";
                String serviceUrl = basePath + fileName;

                String urlpath ;
                if (operatingSystem.equals("Windows")){
                   urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Video\\";
                }else {
                    urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Video/";
                }

                serviceFilePath = urlpath + fileName;// 服务器文件
                FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                // 如果目录中不存在文件，下载雷达文件到temp目录
                File serviceFile = new File(serviceFilePath);// 服务器文件
                if (!serviceFile.exists()) {// 把文件上传到服务器
                    Map<String, Object> queryMap = new HashMap<String, Object>();
                    queryMap.put("id", vdeo.getId());
                    queryMap.put("table_name", "video");
                    queryMap.put("advCode", DbConfig.advCode);
                    queryMap.put("collectionName", "video_file");
                    byte[] data = ms.selectData(queryMap);
                    if (data == null) {
                        serviceFilePath = "";
                    } else {
                        FileUtil.bytesToFile(data, serviceFilePath);
                    }
                }
                if (!serviceFilePath.equals("")) {
                    serviceFilePath = serviceUrl;
                }

                String imagepath = serviceFilePath;
                //添加视频路径
                vdeo.setVideo(imagepath);
            }
        } catch (Exception ex) {
            return new ResultObj("查询成功", ex.getMessage(), true);
        }
        return new ResultObj("查询成功", videos, true);
    }

    /**
     * @Description: 获取农业服务产品
     * nqsrvTypes : '月农用天气预报', '周农用天气预报', '产量预报', '发育期预报', '农事关键期专题', '农业气象服务信息', '农业气象旬月报', '农业气象灾害预警', '病虫害预报'
     * @Author: sunshine
     * @Date: 2021/7/23 16:56
     **/
    @RequestMapping("/GetAgriChanpin")
    @ResponseBody
    public Object GetAgriChanpin(HttpServletRequest request) {
        String nqsrvTypes = request.getParameter("nqsrvTypes");
        Object agrisrvList = farmIndexService.GetAgriChanpin(nqsrvTypes, request);
        return agrisrvList;
    }

    /**
     * @Description: 常规气象服务 nqsrvTypes : '气象专题报', '一周天气预报', '气象信息快报', '重大天气报', '重大气象信息专报'
     * @Author: sunshine
     * @Date: 2021/7/23 17:13
     **/
    @RequestMapping("/GetAgriChanggui")
    @ResponseBody
    public Object GetAgriChanggui(HttpServletRequest request) {
        String nqsrvTypes = request.getParameter("nqsrvTypes");
        Object agrisrvList = farmIndexService.GetAgriChanggui(nqsrvTypes, request);
        return agrisrvList;
    }


    /**
     * @Description: 获取各种类型得区划图
     * @Author: sunshine
     * @Date: 2021/7/23 17:19
     **/
    @RequestMapping("/getQhzhTable")
    @ResponseBody
    public Object getQhzhTable(HttpServletRequest request) {
        String typeName = request.getParameter("typeName");
        Object agrisrvList = farmIndexService.getQhzhTable(typeName, request);
        return agrisrvList;
    }

    /**
     * @Description: 得到预警信息
     * @Author: sunshine
     * @Date: 2021/7/23 17:27
     **/
    @RequestMapping("/getJCWarning")
    @ResponseBody
    public Object getJCWarning(HttpServletRequest request) {
        String id = request.getParameter("id");
        String start = request.getParameter("startDate");
        String end = request.getParameter("endDate");
        Object agrisrvList = farmIndexService.getJCWarning(id, start, end);
        return agrisrvList;
    }
    @RequestMapping("/getWarningInfo")
    @ResponseBody
    public Object getWarningInfo(HttpServletRequest request) {
        Object agrisrvList = farmIndexService.getWarningInfo();
        return agrisrvList;
    }
    /**
     * @Description: 获取监测评估产品图DataTable
     * @Author: sunshine
     * @Date: 2021/7/26 10:13
     **/
    @RequestMapping("/getJcjgList")
    @ResponseBody
    public Object getJcjgList(HttpServletRequest request) {
        String typeName = request.getParameter("typeName");
        Object agrisrvList = farmIndexService.getJcjgList(typeName, request);
        return agrisrvList;
    }

    /**
     * @Description: 得到指标库
     * 作物指标库   zhinames = 1
     * 病虫害指标库   zhinames = 2
     * 气象灾害指标库   zhinames = 3
     * int PageNo, out int rowCount
     * @Author: sunshine
     * @Date: 2021/7/26 10:47
     **/
    @RequestMapping("/getCropIndexlibList")
    @ResponseBody
    public Object getCropIndexlibList(HttpServletRequest request) {
        String zhinames = request.getParameter("zhinames");
        String PageNo = request.getParameter("PageNo");
        Object agrisrvList = farmIndexService.getCropIndexlibList(zhinames, Integer.parseInt(PageNo));
        return agrisrvList;
    }

    /**
     * @Description: 根据大类别获取小类别
     * @Author: sunshine
     * @Date: 2021/7/26 11:17
     **/
    @RequestMapping("/getSmallTypeContent")
    @ResponseBody
    public Object getSmallTypeContent(HttpServletRequest request) {
        String parentId = request.getParameter("parentId");
        String smallId = request.getParameter("smallId");
        if (StringUtil.IsNullOrEmpty(parentId))
            return new ResultObj("查询失败", "parentId不能为空", true);
        Object agrisrvList = farmIndexService.getSmallType(parentId,smallId,request);
        return agrisrvList;
    }

    /**
     * @Description: 得到大小类别
     * @Author: lw
     **/
    @RequestMapping("/getBigType")
    @ResponseBody
    public Object getBigType(HttpServletRequest request) {
        Object bigTypes = farmInfoService.getBigType();
        return bigTypes;
    }
    /**
     * @Description: 根据大类别获取小类别
     * @Author: lw
     **/
    @RequestMapping("/getSmallType")
    @ResponseBody
    public Object getSmallType(HttpServletRequest request) {
        String parentid = request.getParameter("parentId");
        Object smallTypes = farmInfoService.getSmallType(parentid);
        return smallTypes;
    }
    /**
     * @Description: 加载默认站点
     * @Param:
     * @return:
     * @Author: sunshine
     * @Date: 2021/7/22
     **/
    @RequestMapping("/loadDefaultStation")
    @ResponseBody
    public Object loadDefaultStation() {
        List<default_station> default_stationList = farmInfoService.loadDefaultStation();
        ResultObj resultObj = new ResultObj("查询成功", default_stationList, true);
        return resultObj;
    }


    /****
     * 加载农业服务站点
     * @return
     */
    @RequestMapping("/loadNyStation")
    @ResponseBody
    public Object loadNyStation() {
        List<StationInfo> default_stationList = farmInfoService.loadNyStation();
        ResultObj resultObj = new ResultObj("查询成功", default_stationList, true);
        return resultObj;
    }

    /**
     * @Description: 获取县市列表
     * @Author: sunshine
     * @Date: 2021/7/29 13:52
     **/
    @RequestMapping("/getCountyCity")
    @ResponseBody
    public Object getCountyCity() {
        List<county_point> county_points = farmInfoService.getCountyCity();
        ResultObj resultObj = new ResultObj("查询成功", county_points, true);
        return resultObj;
    }

    /**
     * @Description: 获取乡镇列表
     * @Author: sunshine
     * @Date: 2021/7/29 13:55
     **/
    @RequestMapping("/getTownList")
    @ResponseBody
    public Object getTownList(HttpServletRequest request) {
        String county = request.getParameter("county");
        List<country_point> county_points = farmInfoService.getTownList(county);
        ResultObj resultObj = new ResultObj("查询成功", county_points, true);
        return resultObj;
    }

    /**
     * @Description: 获取站点
     * @Author: sunshine
     * @Date: 2021/7/29 13:58
     **/
    @RequestMapping("/getNFList")
    @ResponseBody
    public Object getNFList(HttpServletRequest request) {
        String county = request.getParameter("county");
        String town = request.getParameter("town");
        String type = request.getParameter("type");//农服站0 区域站1
        if(!StringUtil.IsNullOrEmpty(type)&&type.equals("0")){
            List<StationInfo> county_points = farmInfoService.getNFList(county,town);
            ResultObj resultObj = new ResultObj("查询成功", county_points, true);
            return resultObj;
        }else{
            List<smallscale_station> county_points = farmInfoService.getQYList(county,town);
            ResultObj resultObj = new ResultObj("查询成功", county_points, true);
            return resultObj;
        }
    }

    /***
     * 初始化区县
     * @return
     */
    @RequestMapping("/getQuXian")
    @ResponseBody
    public Object getQuXian(HttpServletRequest request) {
        List<String> countys = farmInfoService.getQuXian();
        ResultObj resultObj = new ResultObj("查询成功", countys, true);
        return resultObj;
    }


    /***
     * 得到乡镇信息
     * @return
     */
    @RequestMapping("/GetXiangZheng")
    @ResponseBody
    public Object GetXiangZheng(HttpServletRequest request) {
        String county = request.getParameter("QuXian");
        List<String> towns = farmInfoService.getXiangZheng(county);
        ResultObj resultObj = new ResultObj("查询成功", towns, true);
        return resultObj;
    }

    /***
     * 得到站点信息
     * @return
     */
    @RequestMapping("/getStation")
    @ResponseBody
    public Object getStation(HttpServletRequest request) {
        String county = request.getParameter("QuXian");
        String town = request.getParameter("XiangZheng");
        List<station_info> station = farmInfoService.getStation(county, town);
        ResultObj resultObj = new ResultObj("查询成功", station, true);
        return resultObj;
    }
    /***
     * 获取链接
     * @return
     */
    @RequestMapping("/GetLink")
    @ResponseBody
    public Object GetLink(HttpServletRequest request) {
        List<Links> linksList = farmInfoService.getLinksList();
        try {
            for (Links links : linksList) {
                String serviceFilePath = "";
                // 下载
                String fileName = links.getLinkimg();
                String path = request.getContextPath();
                String basePath = DbConfig.IP + path
                        + "/Temp/Links/";
                String serviceUrl = basePath + fileName;
                String urlpath ;
                if (operatingSystem.equals("Windows")){
                     urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp\\Links\\";
                }else {
                    urlpath = request.getSession().getServletContext().getRealPath("/") + "Temp/Links/";
                }

                serviceFilePath = urlpath + fileName;// 服务器文件
                FileUtil.mkDirs(urlpath);// 创建文件夹，生成多级目录
                FileUtil.ClearTempFiles(urlpath, 1000);// 清除缓存
                // 如果目录中不存在文件，下载图片到temp目录
                File serviceFile = new File(serviceFilePath);// 服务器文件
                if (!serviceFile.exists()) {// 把文件上传到服务器
                    Map<String, Object> queryMap = new HashMap<String, Object>();
                    queryMap.put("id", links.getId());
                    queryMap.put("table_name", "links");
                    queryMap.put("advCode", DbConfig.advCode);
                    queryMap.put("collectionName", "image_file");
                    byte[] data = ms.selectData(queryMap);
                    if (data == null) {
                        serviceFilePath = "";
                    } else {
                        FileUtil.bytesToFile(data, serviceFilePath);
                    }
                }
                if (!serviceFilePath.equals("")) {
                    serviceFilePath = serviceUrl;
                }

                String imagepath = serviceFilePath;
                //添加图片到链接中
                links.setImage(imagepath);
            }
        } catch (Exception ex) {
            return new ResultObj("查询成功", ex.getMessage(), true);
        }
        return new ResultObj("查询成功", linksList, true);
    }

    /***
     * 得到用户名选择
     * @return
     */
    @RequestMapping("/getSelect")
    @ResponseBody
    public Object getSelect(HttpServletRequest request) {
        String msg = farmInfoService.getSelect();
        ResultObj resultObj = new ResultObj("查询成功", msg, true);
        return resultObj;
    }

    /***
     * 获取最近站点
     * @return
     */
    @RequestMapping("/locationSta")
    @ResponseBody
    public Object locationSta(HttpServletRequest request) {
        String lon = request.getParameter("lon");
        String lat = request.getParameter("lat");
        String msg = farmInfoService.locationSta(lon, lat);
        ResultObj resultObj = new ResultObj("查询成功", msg, true);
        return resultObj;
    }
    /**1
     * 三日城镇预报
     * @param request
     * @param model
     * @return
     */
    @RequestMapping("/ThreeDayChenZhenYuBao")
    @ResponseBody
    public Object getThreeDayCityFcst(HttpServletRequest request, Model model) {
        TownshipForecastKey selectKey = new TownshipForecastKey();// 查询类
        String time = DateTime.now().toDateString();// 时间
        String sc = "";
        if(DateTime.now().GetHour() >= 8 && DateTime.now().GetHour() < 20)
            sc = "08";
        else if (DateTime.now().GetHour() >= 0 && DateTime.now().GetHour()<8){
            time = DateTime.now().AddDays(-1).toDateTimeString("yyyy-MM-dd") + " 00:00:00"; // 预报时间
            sc = "20";
        } else{
            sc = "20";
        }
        String strStationID = "";
        String strCountyName = "";
        String ntimes = request.getParameter("ntimes");
        int nTimes;
        List<CityFcstInfo> resultList = new ArrayList<CityFcstInfo>();
        WebCtrlData wcd = new WebCtrlData();
        try {
            selectKey.setTimeChar(sc);
            selectKey.setDateChar(DateTime.parseDate(time).toDate());
            if (!StringUtil.IsNullOrEmpty(ntimes)) {
                selectKey.setNTimes(Integer.parseInt(ntimes));
            }
            List<ForecastInfo> fcstList = qxInfoService.getThreeDayCityFcst(selectKey);
            int count = fcstList.toArray().length;
            for (int i = 0; i < count; i++) {
                strStationID = fcstList.get(i).getStationid();
                strCountyName = fcstList.get(i).getStationname();
                String weather = "";// 天气信息
                String windD = "";// 风向信息
                String windV = "";// 风速信息
                String windS = "";// 风速信息
                String windD12 = wcd.GetAllFx(fcstList.get(i).getWindd1().toString().replace("-65535", "0").trim());
                String windD24 = wcd.GetAllFx(fcstList.get(i).getWindd2().toString().replace("-65535", "0").trim());
                String windV12 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind1())));
                String windV24 = wcd.GetWeatherFs(String.valueOf(WebCtrlData.FengSuToFengJi(fcstList.get(i).getWind2())));
                String windS12 = String.valueOf(fcstList.get(i).getWind1());
                String windS24 = String.valueOf(fcstList.get(i).getWind2());
                if (windD12.equals(windD24)) {
                    windD += windD12;
                } else {
                    windD += windD12 + "转" + windD24;
                }
                if (windV12.equals(windV24)) {
                    windV += windV12;
                } else {
                    windV += windV12 + "~" + windV24;
                }
                if (windS12.equals(windS24)) {
                    windS += windS12 + "m/s";
                } else {
                    windS += windS12 + "~" + windS24 + "m/s";
                }
                if (fcstList.get(i).getWeather1().toString().trim()
                        .equals(fcstList.get(i).getWeather2().toString().trim())) {
                    weather += wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())));
                } else {
                    weather += wcd
                            .GetWeatherTq(String.format("%02d",
                                    Integer.parseInt(fcstList.get(i).getWeather1().toString().trim())))
                            + "转" + wcd.GetWeatherTq(String.format("%02d",
                            Integer.parseInt(fcstList.get(i).getWeather2().toString().trim())));
                }
                double maxTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMaxtemp()));
                double minTemp = Double.parseDouble(String.format("%.1f", fcstList.get(i).getMintemp()));
                String pic1 = String.format("%02d", Integer.parseInt(
                        WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather1().toString().trim())));
                String pic2 = String.format("%02d", Integer.parseInt(
                        WebCtrlData.WeatherNameToPicPath(fcstList.get(i).getWeather2().toString().trim())));
                CityFcstInfo fcstInfo = new CityFcstInfo();
                fcstInfo.setStationId(strStationID);
                fcstInfo.setStationName(strCountyName);
                fcstInfo.setMinTemp(minTemp);
                fcstInfo.setMaxTemp(maxTemp);
                fcstInfo.setRain(fcstList.get(i).getRain());
                fcstInfo.setWindD(windD);
                fcstInfo.setWindV(windV);
                fcstInfo.setWindS(windS);
                fcstInfo.setPic1(pic1);
                fcstInfo.setPic2(pic2);
                fcstInfo.setLat(fcstList.get(i).getLatitude());
                fcstInfo.setLon(fcstList.get(i).getLongitude());
                //
                DmMapPoint dt = transformService.LonLatConvertToLambert(fcstInfo.getLon(), fcstInfo.getLat());
                fcstInfo.setX(dt.x);
                fcstInfo.setY(dt.y);
                fcstInfo.setWeather1(fcstList.get(i).getWeather1().toString().trim());
                fcstInfo.setWeather2(fcstList.get(i).getWeather2().toString().trim());
                fcstInfo.setWeather(weather);
                fcstInfo.setTime(new DateTime(fcstList.get(i).getDatechar()).toDateString());
                resultList.add(fcstInfo);
            }
        } catch (Exception e) {
            // TODO: 城镇预报查询异常
            e.printStackTrace();
            // log.error(e);
        }
        return resultList;
    }

    @RequestMapping(value = "/weatherForecast")
    @ResponseBody
    public Object GetWeatherForecastData(HttpServletRequest request) throws  Exception {
        Object result = "[]";
        String idOrName =request.getParameter("idOrName");// 站点标号  城步编号
        String sc = request.getParameter("sc");// 时次
        String date = request.getParameter("date");// 日期,可用作测试

        //查站点对应的天气预报站点id
        RequestDataBySelect dataBySelect=new RequestDataBySelect();
        dataBySelect.setColumns(new String[]{" stationid,stationname,township,forecaststationid "});
        dataBySelect.setParam("stationname='" + idOrName +"'");
        Map<String,String> map=new HashMap<String, String>();
        map.put("param", JsonUtil.object2Json(dataBySelect));
        map.put("method","station_info");
        map.put("sqlType", "select");
        map.put("advCode", DbConfig.advCode);
        String result1 = pc.processRequest(map);//station_info
        List<station_info> list  = JsonUtil.jsonStr2TypeReference(result1, new TypeReference<List<station_info>>() {});

        if(list.size() <1){
            return  null;
        }
        String  forecaststationid = list.get(0).getForecaststationid();

        result = farmInfoService.getCityWeather(forecaststationid, sc, date);

        return result;
    }

    // 干旱监测
    @RequestMapping("/droughtInitTime")
    @ResponseBody
    public String droughtInitTime() {
        Date date = farmInfoService.droughtInitTime();
        DateTime dt = new DateTime(date);
        return dt.toDateString();
    }

    @RequestMapping("/droughtChart")
    @ResponseBody
    public Object droughtChart(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate1").toString();
        String endDate = request.getParameter("endDate1").toString();
        String stationname = request.getParameter("stationname1");
        List<drought> resultList = farmInfoService.droughtChart(startDate,endDate,stationname);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        List<Float> values1 = new ArrayList<Float>();
        Map<String, List<Float>> stationValMap1 = new HashMap<String, List<Float>>();
        for(int i=0;i<resultList.size();i++){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("MM-dd");
            String time=simpleDateFormat.format(resultList.get(i).getObservationdate());
            hours.add(time);
            values1.add(resultList.get(i).getDryobservationvalue());
        }
        stationValMap1.put(stationname, values1);
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        return result;
    }

    @RequestMapping("/soilChart")
    @ResponseBody
    public Object soilChart(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate").toString();
        String endDate = request.getParameter("endDate").toString();
        String stations = request.getParameter("stationid");
        String stationname = request.getParameter("stationname");
        String level = request.getParameter("level");
        ActualElemQuery elemQuery = new ActualElemQuery();
        if (!StringUtil.IsNullOrEmpty(stations)) {
            String[] split = stations.split(",");
            elemQuery.setStations(Arrays.asList(split));
        }
        List<soil_humidity> resultList = farmInfoService.soilChart(elemQuery,startDate,endDate,level);
        // 处理成曲线图
        List<String> hours = new ArrayList<String>();
        Map<String, List<Double>> stationValMap1 = new HashMap<String, List<Double>>();
        List<Double> values1 = new ArrayList<Double>();
        List<Double> color1 = new ArrayList<Double>();
        for(int i=0;i<resultList.size();i++){
            SimpleDateFormat simpleDateFormat=new SimpleDateFormat("dd HH");
            String time=simpleDateFormat.format(resultList.get(i).getObservetime());
            hours.add(time);
            if(resultList.get(i).getRelhumidity()!=0&&resultList.get(i).getRelhumidity()!=-65535){
                values1.add(resultList.get(i).getRelhumidity());
                color1.add((double)resultList.get(i).getLevel());
            }else {
                values1.add(0.0);
                color1.add((double)resultList.get(i).getLevel());
            }
        }
        stationValMap1.put(stationname, values1);
        stationValMap1.put("color", color1);
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }

        return result;
    }

    // 混合层高度
    @RequestMapping("/soilInitTime")
    @ResponseBody
    public String soilInitTime() {
        Date date = farmInfoService.soilInitTime();
        DateTime dt = new DateTime(date);
        return dt.toDateString();
    }

    @RequestMapping("/checkstaId")
    @ResponseBody
    public Object checkstaId(HttpServletRequest request){
        String staId="";
        String stationName=request.getParameter("stationName");
        staId=farmInfoService.checkId(stationName);
        return staId;
    }

    @RequestMapping("/checkinfo")
    @ResponseBody
    public Object checkInfo(HttpServletRequest request){
        List<cropyield_history> list=new ArrayList<>();
        String stationId=request.getParameter("stationId");
        list=farmInfoService.checkInfo(stationId);

        return list;
    }

    /**
     * 添加雨量统计图
     *
     * @param request
     * @param model
     * @return
     * @author dsq
     * @throws ParseException
     * @date 2018年7月13日
     */
    @RequestMapping("/addRWChart")
    @ResponseBody
    public Object addRainChart(HttpServletRequest request, Model model) throws Exception {
        Date startDate = DateTime.parseDateTime(request.getParameter("startDate")).toDate();
        Date endDate = DateTime.parseDateTime(request.getParameter("endDate")).toDate();
        String stationname = request.getParameter("citys");
        String element = request.getParameter("element");
        //根据站点 找到 对应实况的站点
        RequestDataBySelect dataBySelect=new RequestDataBySelect();
        dataBySelect.setColumns(new String[]{" stationid,stationname,smallscalestationid "});
        dataBySelect.setParam("stationname='" + stationname +"'");
        Map<String,String> map=new HashMap<String, String>();
        map.put("param", JsonUtil.object2Json(dataBySelect));
        map.put("method","station_info");
        map.put("sqlType", "select");
        map.put("advCode", DbConfig.advCode);
        String result1 = pc.processRequest(map);//station_info
        List<station_info> list  = JsonUtil.jsonStr2TypeReference(result1, new TypeReference<List<station_info>>() {});
        if(list.size() <1){
            return  null;
        }
        String  Smallscalestationid = list.get(0).getSmallscalestationid();   //得到实况站点id


        ActualElemQuery elemQuery = new ActualElemQuery();
        elemQuery.setStations(Arrays.asList(Smallscalestationid));
        elemQuery.setElement(element);
        elemQuery.setStartDate(startDate);
        elemQuery.setEndDate(endDate);
        List<ActualData> resultList = farmInfoService.qxElementQuery(elemQuery);
        // 处理成曲线图
        List<Integer> hours = new ArrayList<Integer>();
        Map<String, List<Double>> stationValMap = new HashMap<String, List<Double>>();
        for (ActualData actualData : resultList) {
            String stationName = actualData.getStationName().trim();
            if (stationName.equals(resultList.get(0).getStationName().trim())) {
                hours.add(new DateTime(actualData.getDateTime()).GetHour());
            }
            double value = 0d;
            switch (element) {
                case "rain":
                    value = actualData.getRain();
                    break;
                case "temp":
                    value = actualData.getTemp();
                    break;
                case "winds":
                    value = actualData.getWinds();
                    break;
                case "humid":
                    value = actualData.getHumid();
                    break;
                case "pressure":
                    value = actualData.getPressure();
                default:
                    break;
            }
            if (!stationValMap.keySet().contains(stationName)) {
                List<Double> values = new ArrayList<Double>();

                values.add(value);
                stationValMap.put(stationName, values);
            } else {
                stationValMap.get(stationName).add(value);
            }
        }
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(stationname);
            tempArr.add(stationValMap.get(key));
            result.add(tempArr);
        }
        return result;
    }
    @RequestMapping("/createChart")
    @ResponseBody
    public Object createChart(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate").toString();
        String endDate = request.getParameter("endDate").toString();
        String stations = request.getParameter("stationId");
        String element = request.getParameter("element");
        String chartType = request.getParameter("chartType");
        String type=request.getParameter("type");
        ActualElemQuery elemQuery = new ActualElemQuery();
        if (!StringUtil.IsNullOrEmpty(stations)) {
            String[] split = stations.split(",");
            elemQuery.setStations(Arrays.asList(split));
        }
        elemQuery.setElement(element);
        elemQuery.setType(chartType);
        List<cropyield_history> resultList = farmInfoService.createChart(elemQuery,type,startDate,endDate);
        List<cropyield_history> resultList1 = farmInfoService.createChart1(elemQuery,type,startDate,endDate);
        // 处理成曲线图
        List<Integer> hours = new ArrayList<Integer>();
        Map<String, List<Double>> stationValMap1 = new HashMap<String, List<Double>>();
        Map<String, List<Double>> stationValMap2 = new HashMap<String, List<Double>>();
        int start=Integer.parseInt(startDate);
        int end=Integer.parseInt(endDate);
        int falg=0;
        int falg1=0;
        List<Double> values1 = new ArrayList<Double>();
        List<Double> values2 = new ArrayList<Double>();
        for(;start<=end;start++){
            hours.add(start);
            if(resultList.size() > falg &&resultList.get(falg).getYear()==start){
                values1.add(resultList.get(falg).getYield());
                falg++;
            }else {
                values1.add(0.0);
            }
            if(resultList1.size()> falg1 &&resultList.get(falg1).getYear()==start){//resultList1.size()!=0
                values2.add(resultList1.get(falg1).getYield());
                falg1++;
            }else {
                values2.add(0.0);
            }
        }
        stationValMap1.put("实况", values1);
        stationValMap2.put("预报", values2);
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        for (String key : stationValMap2.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap2.get(key));
            result.add(tempArr);
        }
        return result;
    }

    @RequestMapping("/growChart")
    @ResponseBody
    public Object growChart(HttpServletRequest request, Model model) throws ParseException {
        String startDate = request.getParameter("startDate").toString();
        String endDate = request.getParameter("endDate").toString();
        String stations = request.getParameter("stationId");
        String element = request.getParameter("element");
        String type=request.getParameter("type");
        String datename=request.getParameter("datename");
        ActualElemQuery elemQuery = new ActualElemQuery();
        if (!StringUtil.IsNullOrEmpty(stations)) {
            String[] split = stations.split(",");
            elemQuery.setStations(Arrays.asList(split));
        }
        elemQuery.setStations(Arrays.asList(stations));
        elemQuery.setElement(element);
        List<crop_growdate_history> resultList = farmInfoService.growChart(elemQuery,type,startDate,endDate,datename);
        List<crop_growdate_history> resultList1 = farmInfoService.growChart1(elemQuery,type,startDate,endDate,datename);
        // 处理成曲线图
        List<Integer> hours = new ArrayList<Integer>();
        Map<String, List<String>> stationValMap1 = new HashMap<String, List<String>>();
        Map<String, List<String>> stationValMap2 = new HashMap<String, List<String>>();
        int start=Integer.parseInt(startDate);
        int end=Integer.parseInt(endDate);
        List<String> values1 = new ArrayList<String>();
        List<String> values2 = new ArrayList<String>();
        int flag1=0;
        int flag2=0;
        List<String> date=new ArrayList<>();
        List<String> date1=new ArrayList<>();
        for (; start <= end; start++) {
            hours.add(start);

            // 检查 flag1 是否在有效范围内
            if (resultList.get(flag1).getYear() == start) {
                date.add(resultList.get(flag1).getGrowdatedate());
                flag1++;
            } else {
                date.add("暂无数据！");
            }

            // 检查 flag2 是否在有效范围内
            if ( resultList1.get(flag2).getYear() == start) {
                date1.add(resultList1.get(flag2).getForecastdate());
                flag2++;
            } else {
                date1.add("暂无数据！");
            }
        }
        stationValMap1.put("实况日期",date);
        stationValMap2.put("预报日期",date1);
        ArrayList<Object> result = new ArrayList<Object>();
        result.add(hours);
        for (String key : stationValMap1.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap1.get(key));
            result.add(tempArr);
        }
        for (String key : stationValMap2.keySet()) {
            ArrayList<Object> tempArr = new ArrayList<Object>();
            tempArr.add(key);
            tempArr.add(stationValMap2.get(key));
            result.add(tempArr);
        }
        return result;
    }
}
